package com.atde._04_structural_design_patterns.proxy.cglib;


import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @BelongsProject: hsp_java_design_mode
 * @BelongsPackage: com.atde._04_structural_design_patterns.proxy.cglib
 * @Author: Del
 * @CreateTime: 2025-06-24  19:21
 * @Description: 代理模式 --- cglib 代理
 * @Version: 1.0
 */
public class ProxyFactory implements MethodInterceptor {

    // 目标对象
    private Object target;

    // 构造器，传入目标对象
    public ProxyFactory (Object target) {
        this.target = target;
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("Cglib代理模式... 开始代理");
        Object invoke = method.invoke(target, objects);
        System.out.println("Cglib代理模式... 结束代理");

        return invoke;
    }

    // 返回一个代理镀锡，是 target 的代理对象
    public Object getProxyInstance() {
        // 1. 创建一个工具类
        Enhancer enhancer = new Enhancer();
        // 2. 设置父类
        enhancer.setSuperclass(target.getClass());
        // 3. 设置回调函数
        enhancer.setCallback(this);
        // 4. 创建子类对象，即代理对象
        return enhancer.create();
    }
}
